/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.serviceapp.service.stores.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.qinyeit.serviceapp.entity.*;
import com.qinyeit.serviceapp.entity.enums.*;
import com.qinyeit.serviceapp.exception.BusinessRunTimeException;
import com.qinyeit.serviceapp.repository.stores.InventoryOrderDetailRepository;
import com.qinyeit.serviceapp.repository.stores.InventoryOrderRepository;
import com.qinyeit.serviceapp.service.dishes.DishesStoreService;
import com.qinyeit.serviceapp.service.materials.MaterialService;
import com.qinyeit.serviceapp.service.stores.*;
import com.qinyeit.serviceapp.utils.CompuUtils;
import com.qinyeit.serviceapp.utils.LocalUtils;
import com.qinyetech.springstage.core.date.DateUtils;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.service.BaseService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.List;

/** 
 * ClassName: InventoryOrderServiceImpl <br/> 
 * Function: 盘点单据 业务实现 <br/> 
 * date: 2018-11-08 11:29:40 <br/> 
 * 
 * @author liuwenjin
 * @version 1.0
 * @since JDK 1.8
 */
@Service
@Transactional
public class InventoryOrderServiceImpl extends BaseService<InventoryOrder, Long> implements InventoryOrderService {


	@Autowired
	private InventoryOrderRepository inventoryOrderRepository;
	@Autowired
	private MaterialService materialService;
	@Autowired
	private StockService stockService;
	@Autowired
	private InventoryOrderDetailRepository inventoryOrderDetailRepository;
	@Autowired
	private StoreInOrderService storeInOrderService;
	@Autowired
	private StoreInOrderDetailService storeInOrderDetailService;
	@Autowired
	private StoreOutOrderService storeOutOrderService;
	@Autowired
	private StoreOutOrderDetailService storeOutOrderDetailService;
	@Autowired
	private DishesStoreService dishesStoreService;


	@Override
	public void saveData(JSONObject data, Long merchantGroupId) {
		if(data==null){
			throw new BusinessRunTimeException("订单信息为空",10001);
		}
		JSONObject orderData = data.getJSONObject("inventoryOrders");
		if(orderData==null){
			throw new BusinessRunTimeException("订单信息为空",10001);
		}

		JSONArray detailData = data.getJSONArray("details");
		if(CollectionUtils.isEmpty(detailData)){
			throw new BusinessRunTimeException("订单明细为空",10002);
		}

		Long id = orderData.getLong("id");
		InventoryOrder inventoryOrder = null;
		if(id==null){
			//保存
			inventoryOrder = new InventoryOrder();
			inventoryOrder.setNo(LocalUtils.getOrderNo());
		}else {
			//编辑
			inventoryOrder = this.findById(id);
			//删除明细
			inventoryOrderRepository.deleteOrderDetails(id,merchantGroupId);

		}
		inventoryOrder.setNotMode(NotMode.valueOf(orderData.getString("notMode")));
		inventoryOrder.setType(InventoryType.valueOf(orderData.getString("type")));
		inventoryOrder.setWarehouseId(orderData.getLong("warehouseId"));
		inventoryOrder.setWarehouseName(orderData.getString("warehouseName"));
		inventoryOrder.setRemark(orderData.getString("remark"));
		inventoryOrder.setMerchantGroupId(merchantGroupId);
		inventoryOrder.setAuditTime(DateUtils.date());

		DishesStore store = dishesStoreService.findById(orderData.getLong("storeId"));
		inventoryOrder.setStoreId(store.getId());
		inventoryOrder.setStoreName(store.getName());

		int type = data.getInteger("type");
		if(type==1){
			//保存
			inventoryOrder.setState(InventoryState.NOAUDIT);
		}else if(type == 2) {
			//提交并审核
			inventoryOrder.setState(InventoryState.AUDIT);
		}

		JSONObject item ;
		List<InventoryOrderDetail> detailList = Lists.newArrayList();
		Material material = null;
		InventoryOrderDetail detail = null;
		Stock stock = null;
		for (int i = 0; i < detailData.size(); i++) {
			item = detailData.getJSONObject(i);
			material = materialService.findById(item.getLong("materialId"));
			detail=new InventoryOrderDetail();
			detail.setMerchantGroupId(inventoryOrder.getMerchantGroupId());
			detail.setOrder(inventoryOrder);
			detail.setMaterialId(material.getId());
			detail.setNo(material.getNo());
			detail.setName(material.getName());
			detail.setUnit(material.getUnit());
			detail.setSpec(material.getGoodsSpec());
			detail.setCode(material.getCode());
			//查询理论的库存数量和成本均价
			stock = stockService.getStocks(inventoryOrder.getWarehouseId(), material.getId(),merchantGroupId);
			if(stock==null){
				throw new BusinessRunTimeException("仓库中不存在物料["+material.getName()+"]", 1002);
			}
			detail.setPrice(stock.getCost());
			detail.setCount(stock.getCount());

			//盘点数量 实盘数量
			detail.setRealCount(item.getDouble("realCount"));

			if(detail.getRealCount()==null){
				detail.setMark(false);
				if(inventoryOrder.getNotMode()==NotMode.STORE){
					//按照库存处理
					detail.setRealCount(detail.getCount());
				}else if(inventoryOrder.getNotMode()==NotMode.ZORE){
					//按零处理
					detail.setRealCount(0d);
				}
				detail.setMark(false);
			}else{
				detail.setMark(true);
			}

			detail.setAmount(detail.getPrice()*detail.getRealCount());
			detail.setRemark(item.getString("memo"));
			detailList.add(detail);
		}
		inventoryOrderDetailRepository.saveAll(detailList);
		inventoryOrder = this.update(inventoryOrder);

		if(inventoryOrder.getState()==InventoryState.AUDIT){
			this.saveStore(inventoryOrder,detailList);
		}
	}

	//保存 入库单和出库单  报损出库 ./ 溢出入库
	private void saveStore(InventoryOrder inventoryOrder,List<InventoryOrderDetail> inventoryOrderDetails){
		List<InventoryOrderDetail> jiaDetails=Lists.newArrayList();
		List<InventoryOrderDetail> jianDetails=Lists.newArrayList();
		for(InventoryOrderDetail detail : inventoryOrderDetails){
			if(CompuUtils.compareTo(detail.getRealCount(),detail.getCount()) == 0 ){
				//实盘数量等于库存数量
				continue;
			}
			//实盘数量不等于库存数量
			if(CompuUtils.compareTo(detail.getRealCount(),detail.getCount())==1){
				jiaDetails.add(detail);
			}else if(CompuUtils.compareTo(detail.getRealCount(),detail.getCount())==-1){
				jianDetails.add(detail);
			}
		}
		Material material = null;
		Stock stock ;
		if(jiaDetails.size()>0){
			StoreInOrder storeInOrder=new StoreInOrder();
			storeInOrder.setMerchantGroupId(inventoryOrder.getMerchantGroupId());
			storeInOrder.setInTime(DateUtils.date());
			storeInOrder.setNo(LocalUtils.getOrderNo());
			storeInOrder.setState(StoreInState.AUDIT);
			storeInOrder.setWarehouseId(inventoryOrder.getWarehouseId());
			storeInOrder.setWarehouseName(inventoryOrder.getWarehouseName());
			storeInOrder.setRemark("");
			storeInOrder.setType(StoreInType.YICHUIN);
			storeInOrder.setStoreId(inventoryOrder.getStoreId());
			storeInOrder.setStoreName(inventoryOrder.getStoreName());
			storeInOrder = storeInOrderService.save(storeInOrder);
			double money=0d;
			StoreInOrderDetail inDetail;
			for(InventoryOrderDetail detail : jiaDetails){
				//保存记录更改
				material = materialService.findById(detail.getMaterialId());
				inDetail=new StoreInOrderDetail();
				inDetail.setMerchantGroupId(inventoryOrder.getMerchantGroupId());
				inDetail.setOrder(storeInOrder);
				inDetail.setMaterialId(detail.getMaterialId());
				inDetail.setNo(detail.getNo());
				inDetail.setName(detail.getName());
				inDetail.setSpec(detail.getSpec());
				inDetail.setStorageUnit(detail.getUnit());
				inDetail.setStoragePrice(detail.getPrice());
				inDetail.setStorageCount(Math.abs(detail.getRealCount()-detail.getCount()));
				inDetail.setStorageTotal(inDetail.getStorageCount()*inDetail.getStoragePrice());
				inDetail.setCode(detail.getCode());
				money = CompuUtils.add(money,inDetail.getStorageTotal());
				storeInOrderDetailService.save(inDetail);

				//保存库存
				stock = stockService.getStocks(inventoryOrder.getWarehouseId(),detail.getMaterialId(),inventoryOrder.getMerchantGroupId());
				if(stock==null){
					stock = new Stock();
					stock.setCost(material.getOrderPriceBom());
					stock.setCount(inDetail.getStorageCount());
					stock.setAmount(CompuUtils.multiply(stock.getCount(),stock.getCost()));
					stock.setWarehouseId(inventoryOrder.getWarehouseId());
					stock.setMaterialId(detail.getMaterialId());
				}else {
					stock.setCount(CompuUtils.add(stock.getCount(),inDetail.getStorageCount()));
					stock.setAmount(CompuUtils.multiply(stock.getCount(),stock.getCost()));
				}
				stockService.update(stock);
			}
			storeInOrder.setAmount(money);
			storeInOrderService.save(storeInOrder);
		}

		if(jianDetails.size()>0){
			StoreOutOrder storeOutOrder=new StoreOutOrder();
			storeOutOrder.setMerchantGroupId(inventoryOrder.getMerchantGroupId());
			storeOutOrder.setOutTime(DateUtils.date());
			storeOutOrder.setNo(LocalUtils.getOrderNo());
			storeOutOrder.setState(StoreOutState.AUDIT);
			storeOutOrder.setWarehouseId(inventoryOrder.getWarehouseId());
			storeOutOrder.setOperatorName(inventoryOrder.getWarehouseName());
			storeOutOrder.setRemark("");
			storeOutOrder.setType(StoreOutType.YICHUOUT);
			storeOutOrder.setOperator(null);
			storeOutOrder.setOperatorName("");
			storeOutOrder.setChecker(null);
			storeOutOrder.setCheckerName("");
			storeOutOrder = storeOutOrderService.save(storeOutOrder);
			storeOutOrder.setStoreId(inventoryOrder.getStoreId());
			storeOutOrder.setStoreName(inventoryOrder.getStoreName());
			StoreOutOrderDetail outDetail;

			double money=0d;
			for(InventoryOrderDetail detail : jianDetails){
				outDetail = new StoreOutOrderDetail();
				outDetail.setMerchantGroupId(inventoryOrder.getMerchantGroupId());
				outDetail.setOrder(storeOutOrder);
				outDetail.setMaterialId(detail.getId());
				outDetail.setName(detail.getName());
				outDetail.setNo(detail.getNo());
				outDetail.setUnit(detail.getUnit());
				outDetail.setSpec(detail.getSpec());
				outDetail.setPrice(detail.getPrice());
				outDetail.setCount(Math.abs(detail.getCount()-detail.getRealCount()));
				outDetail.setTotal(outDetail.getPrice()*outDetail.getCount());
				outDetail.setCode(detail.getCode());
				money = CompuUtils.add(money,outDetail.getTotal());
				storeOutOrderDetailService.save(outDetail);

				//保存库存
				stock = stockService.getStocks(inventoryOrder.getWarehouseId(),detail.getMaterialId(),inventoryOrder.getMerchantGroupId());
				if(stock==null){
					throw new BusinessRunTimeException("商品["+outDetail.getName()+"]没有库存",10005);
				}else {
					stock.setCount(CompuUtils.add(stock.getCount(),outDetail.getCount()*(-1)));
					stock.setAmount(CompuUtils.multiply(stock.getCount(),stock.getCost()));
				}
				stockService.update(stock);
			}
			storeOutOrder.setAmount(money);
			storeOutOrderService.save(storeOutOrder);
		}

	}
}